<?php
include 'config.php';
include 'functions.php';

if (!defined('DEBUG') && !isset($_REQUEST['signed_request']))
    header('Location: ' . $redirect_uri);

$signed_request = '';
$signed_request_string = '';
if (defined('DEBUG')) {
    $signed_request_string = 'CaJeByGCcKSS6R_5zq0DETcEQ7VLwYyov0SKFxUR9Qw.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNTUzNDI0MDAsImlzc3VlZF9hdCI6MTM1NTMzNjUwMCwib2F1dGhfdG9rZW4iOiJBQUFGVmJZZ1BhM29CQU1iWkFNVE9TeUQ5bkNOdFJ5ekxXZ3RUeUxaQ0R4VFhrVXlMeXlxQW5pTFRqT2h1T2VUQXpqM0p0cEo1c01QcDVhUDlxUHlhSEZWYXBDenJMTVlOME0xSWhaQjA0OG9pczZjM2F4bCIsInVzZXIiOnsiY291bnRyeSI6InBsIiwibG9jYWxlIjoiZW5fVVMiLCJhZ2UiOnsibWluIjoyMX19LCJ1c2VyX2lkIjoiMTc1OTE2MTUxMyJ9';
} else {
    if (isset($_REQUEST['signed_request']))
        $signed_request_string = $_REQUEST['signed_request'];
}
$signed_request = '?signed_request=' . $signed_request_string;

$user_array = array();
if (!empty($signed_request_string))
    $user_array = parse_signed_request($signed_request_string);

$connected = false;
if (isset($user_array['user_id']))
    $connected = true;
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Find gifts for Christmas</title>
        <meta name="description" content="">
        <meta name="author" content="">

        <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
        <!--[if lt IE 9]>
          <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->

        <!-- Le styles -->
        <link rel="stylesheet" type="text/css" href="bootstrap.css">
        <link rel="stylesheet" href="css/fontello.css">
        <!--[if IE 7]>
        <link rel="stylesheet" href="css/fontello-ie7.css">
        <![endif]-->
        <?php if (defined('DEBUG')): ?>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
        <?php else: ?>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <?php endif; ?>
        <link rel="stylesheet" href="css/redmond/jquery-ui-1.9.2.custom.css" />
        <script src="js/jquery-ui-1.9.2.custom.js"></script>

        <script src="js/bootstrap-modal.js"></script>
        <?php include 'js/script.php'; ?>

    </head>
    <body>
        <?php include 'google-analytics.php'; ?>
        <div id="fb-root"></div>
        <?php // include 'js/facebook.php';    ?>
        <script>
            window.debug = false;
            
            $(document).ready(function(){
                
                //bonus:
                $('.media-grid>li').append('<small style="position: absolute;top: -10px;left: 196px;opacity:0">Why so serious?</small>');
                $('.media-grid>li>small').click(function(){
                    var santa = $('img.santa');
                    if(santa.hasClass('bonus')){
                        santa.removeClass('bonus');
                        santa.attr('src', 'img/santa_girl.png');
                    }else{
                        santa.addClass('bonus');
                        santa.attr('src', 'img/santa_girl2.png');
                    }
                });
                // Auth redirect
                $('a.primary.auth').click(function(){
                    top.location.href='<?php echo $auth_url; ?>';
                });
                
                
                function recalc_sliders(){
                    $('div.product').each(function(index){
                    
                        var n_slides = $(this).find('.slide').length;
                        var slide = 1;
                        var slide_width = $(this).find('.slide').width();
                        var product = $(this);
                        
                        if(n_slides<2){
                            product.find('i').css('visibility', 'hidden');
                        }else{
                            $(this).find('.icon-right-open').unbind('click');
                            $(this).find('.icon-right-open').click(function(){
                                if(slide<n_slides){
                                    slide++;
                                    product.find('.wrapper').animate({
                                        'left': '-='+slide_width
                                    }, 500);
                            
                                    if(slide==n_slides){
                                        $(this).css('opacity', '.3');
                                        product.find('.icon-left-open').css('opacity', '1');
                                    }
                                }
                            });
                            $(this).find('.icon-left-open').unbind('click');
                            $(this).find('.icon-left-open').click(function(){
                                if(slide>1){
                                    slide--;
                                    product.find('.wrapper').animate({
                                        'left': '+='+slide_width
                                    }, 500);
                            
                                    if(slide==1){
                                        $(this).css('opacity', '.3');
                                        product.find('.icon-right-open').css('opacity', '1');
                                    }
                                }
                            });
                        }
                    });
                }
                recalc_sliders();
                //End of slider
                
                // Love-Hate actions
                window.next_product = 0;
                window.n_choosen = 0;
                
                if( $('.presents.you').size() ){
                    $('.product').css('opacity', '0');
                    
                    var request_url = 'bigdata/helpSanta.php';
                    var extra_data = {};
                    if(window.debug){
                        console.log('what I send:');
                        console.log(extra_data);
                    }
                    $.post(request_url, extra_data, function(data) {
                        if(window.debug){
                            console.log('what I get:');
                            console.log(data);
                            console.log(window.user_id);
                        }
                        
                        window.recommendations = data.recommendations;
                        window.next_page_url = data.next;
                        
                        //Trigger image link for colecting extra data:
                        $('.slide>a').live("mouseup", function(e){
                            
                            if( e.which == 1 || e.which == 2 )
                                if( typeof $(this).attr('dir') != 'undefined' ){
                                    var extra_data = {
                                        recommendation_id : data.recommendation_id,
                                        product_id : $(this).attr('dir')
                                    };
                                $.post('bigdata/countClick.php', extra_data, function(data) {
                                    if(data.status != 'success'){
                                        console.log('countClick.php error');
                                        console.log(info);
                                    }
                                }, 'json');
                            }
                        });
                        
                        $.each(data.recommendations, function(index, element){
                            if(index<4){
                                product =  $('.product').eq(index);
                                product.find('h3').text(element.title);
                                product.find('img').attr('src', element.mediumimagelink);
                                product.find('a').attr('href', element.amazonurl);
                                product.find('.lovehate a').attr('href', element.id);
                                product.find('a').attr('dir', element.id);
                                window.next_product++;
                                product.animate({opacity: '1'}, 500*index);
                            }
                        });
                    }, "json");
                }
                
                $('.lovehate a').live().click(function(){
                    //                    console.log(window.next_product);
                    var slide = $(this).parents('.slide');
                    var link_obj = $(this);
                    
                    slide.animate({
                        'opacity': 0
                    }, 1000, function(){
                        // part to send information
                        var request_url = 'bigdata/rateProduct.php';
                        
                        var reaction = true;
                        if( link_obj.hasClass('danger') )
                            reaction = false;
                        
                        var extra_data = {
                            item_id : link_obj.attr('href'),
                            user_id : window.user_id,
                            positive : reaction
                        };
                        if(window.debug){
                            console.log('what I send:');
                            console.log(extra_data);
                        }
                        $.post(request_url, extra_data, function(data) {
                            if(window.debug){
                                console.log('what I get:');
                                console.log(data);
                            }
                        }, "json");
                        
                        /*
                         * Count how many products was choosen
                         */
                        window.n_choosen++;
                        if(window.n_choosen == 5){
                            FB.ui(
                            {
                                method: 'feed',
                                name: 'Click if you want find gift for you or your friends!',
                                caption: 'Fast and app for free',
                                description: (
                                'Connect with app and find perfect gifts! ' +
                                    'Now!'
                            ),
                                link: 'http://apps.facebook.com/findgiftsforfriends/',
                                picture: 'http://bigdata.ii4b.com/img/santa_girl_128.png'
                            },
                            function(response) {
                                if (response && response.post_id) {
                                    alert('Thanks! Your post was published.');
                                } else {
                                    alert('Your post was not published ;(');
                                }
                            }
                        );
                        }
                        
                        
                        // part of display next element
                        if(window.recommendations.length <= window.next_product){
                            
                            //get next page and merge it
                            if(window.next_page_url !== null){
                                
                                $.post(window.next_page_url, {}, function(data) {
                                    
                                    window.next_page_url = data.next;
                        
                                    if(data.recommendations != null){
                                        //merge products
                                        window.recommendations = $.merge(window.recommendations, data.recommendations);
                                        
                                        $.each(window.recommendations, function(index, element){
                                            if(index==window.next_product){
                                                slide.find('h3').text(element.title);
                                                slide.find('img').attr('src', element.mediumimagelink);
                                                slide.find('a').attr('href', element.amazonurl);
                                                slide.find('.lovehate a').attr('href', element.id);
                                                slide.find('a').attr('dir', element.id);
                                            }
                                        });
                                        window.next_product++;
                                        
                                    }else{
                                        // no more pages
                                        // message about end of products vector
                                        slide.find('h3').text('No more products, sorry..')
                                        slide.find('.lovehate').hide();
                                        slide.find('img').remove();
                                        slide.parents('.product').delay(5000).animate({opacity: '0'}, 500, function(){ 
                                            $(this).css('visibility', 'hidden')
                                        });
                                    }
                                }, "json");
                            }else{
                                // if not more link to ask for data
                                slide.find('h3').text('No more products, sorry..')
                                slide.find('.lovehate').hide();
                                slide.find('img').remove();
                                slide.parents('.product').delay(5000).animate({opacity: '0'}, 500, function(){ 
                                    $(this).css('visibility', 'hidden')
                                });
                            }
                        }else{
                            // if we have more products in our vector
                            $.each(window.recommendations, function(index, element){
                                if(index==window.next_product){
                                    slide.find('h3').text(element.title);
                                    slide.find('img').attr('src', element.mediumimagelink);
                                    slide.find('a').attr('href', element.amazonurl);
                                    slide.find('.lovehate a').attr('href', element.id);
                                    slide.find('a').attr('dir', element.id);
                                }
                            });
                            window.next_product++;
                        }
                        
                        $(this).animate({
                            'opacity': 1
                        }, 1000);
                        
                    });
                    return false;
                });
        
                // Send info from extra-form:
                $('#extra-form form').submit(function(e){
                    
                    var friend_id = $('#extra-form input[name=friend_id]').val(); //get from submit?
                    
                    var show_again = new Object();
                    //check if likes are displayed:
                    if( $('.product.likes').css('display') == 'block' )
                        show_again.likes = true;
                    if( $('.product.age').css('display') == 'block' )
                        show_again.age = true;
                    if( $('.product.gender').css('display') == 'block' )
                        show_again.gender = true;
                    
                    if(window.debug){
                        console.log('show_again');
                        console.log(show_again);
                    }
                        
                    window.startLoading(null, friend_id, $(this).serialize(), 'bigdata/getFormRecommendations.php', show_again);
                    
                    return false;
                });
                
                $('#backto_friends_avatars').click(function(){
                    $('#extra-form').hide();
                    $('.friends_avatars, .friends_avatars_label').css('opacity', '0').show().animate({
                        opacity: '1'
                    });
                });
                
                // name - name of the user(label)
                // id - user_uid
                // extra_data - data send via post
                // request_url - url where post is send
                // show_again - which of category box, show again, without refresh
                window.startLoading = function(name, id, extra_data, request_url, show_again, show_quiz){
                    // default params
                    //                    extra_data = typeof extra_data !== 'undefined' ? a : 42;
                    show_quiz = typeof show_quiz !== 'undefined' ? show_quiz : true;
                    
                    var photo_url = 'https://graph.facebook.com/'+id+'/picture';
                    if(name!=null){
                        $('.page-header i').html( '<img src="'+photo_url+'"/> '+name);
                        $('i.name').text(name);
                    }
                
                    $('.presents>div.loading').show();
                    $('.presents>div.product').hide();
                    $('.presents>div.connect').hide();
                    
                    // Hide form and every label
                    $('#extra-form').hide();
                    $('#extra-form .clearfix>label').hide().next().hide();
            
                    // Unbind previous action
                    $('.slide>a').die("mouseup");
        
                    // Ajax request for data
                    request_url = typeof request_url !== 'undefined' ? request_url : 'bigdata/getRecommendations.php';
                    extra_data = typeof extra_data !== 'undefined' ? extra_data : {friend_id:id};
                    
                    if(window.debug){
                        console.log('what I send to '+request_url);
                        console.log(extra_data);
                    }
                    
                    $.post(request_url, extra_data, function(data) {
                    
                        if(window.debug){
                            console.log('what I get');
                            console.log(data);
                        }
                        // Check for errors and redirects urls exist
                        if( !window.debug && typeof data.redirect_url !== 'undefined' ){
                            top.location.href=data.redirect_url;
                        }
                            
                        // Set hidden inputs for extra form
                        $('#extra-form input[name=friend_id]').val(id);
                        $('#extra-form input[name=sex]').val(data.additionalInfo.sex);
                        
                        
                        //Trigger image link for colecting extra data:
                        $('.slide>a').live("mouseup", function(e){
                            
                            if( e.which == 1 || e.which == 2 )
                                if( typeof $(this).attr('dir') != 'undefined' ){
                                
                                    var extra_data = {
                                        recommendation_id : data.recommendation_id,
                                        product_id : $(this).attr('dir')
                                    };
                                $.post('bigdata/countClick.php', extra_data, function(data) {
                                    if(data.status != 'success'){
                                        console.log('countClick.php error');
                                        console.log(info);
                                    }
                                }, 'json');
                            }
                        });
                        
                    
                        //template of single slide
                        var slide = $('.slide').eq(0).clone();
                    
                        // Show and set likes box
                        if( typeof show_again !== 'undefined' && typeof show_again.likes !== 'undefined'){
                            $('.product.likes').show();
                        }else if(data.likes == null){
                            if(name!=null)
                                $('#extra-form label[for=likes] i').text( name.split(' ')[ 0 ] );
                    
                            // reset and set good checkboxes
                            $('#extra-form .inputs-list').hide();
                            if( data.additionalInfo.sex == 'K' )
                                $('#extra-form .inputs-list.female').show();
                            else
                                $('#extra-form .inputs-list.male').show();
                    
                            $('#extra-form label[for=likes]').show().next().show();
                        }else{
                            //reset wrapper
                            $('.product.likes .wrapper').empty().css('left', '0px');
                            
                            if( data.additionalInfo.sex == 'K' )
                                $('.product.likes h2').text('According to her likes');
                            else
                                $('.product.likes h2').text('According to his likes');
                        
                            $.each(data.likes, function(i, n){
                                var product = slide.clone();
                                product.find('h3').text(n.title);
                                product.find('img.product_photo').attr('src', n.mediumimagelink);
                                product.find('a').attr('href', n.amazonurl);
                                product.find('a').attr('dir', n.id);
                                $('.product.likes .wrapper').append(product);
                            });
                            $('.product.likes').show();
                        }
                        
                        // Show and set gender box
                        if( typeof show_again !== 'undefined' && typeof show_again.gender !== 'undefined'){
                            $('.product.gender').show();
                        }else if(data.gender == null){
                            // there is no more input for gender
                        }else{
                            $('.product.gender .wrapper').empty().css('left', '0px');
                            
                            if( data.additionalInfo.sex == 'K' )
                                $('.product.gender h2').text('According to her sex');
                            else
                                $('.product.gender h2').text('According to his sex');
                        
                            $.each(data.gender, function(i, n){
                                var product = slide.clone();
                                product.find('h3').text(n.title);
                                product.find('img.product_photo').attr('src', n.mediumimagelink);
                                product.find('a').attr('href', n.amazonurl);
                                product.find('a').attr('dir', n.id);
                                $('.product.gender .wrapper').append(product);
                            });
                            $('.product.gender').show();
                        }
                        
                        // Show and set box for age
                        if( typeof show_again !== 'undefined' && typeof show_again.age !== 'undefined'){
                            $('.product.genderage').show();
                        }else if(data.genderage == null){
                            $('#extra-form label[for=age]').show().next().show();
                        }else{
                            $('.product.genderage .wrapper').empty().css('left', '0px');
                            
                            if( data.additionalInfo.sex == null && data.additionalInfo.age != null)
                                $('.product.genderage h2').text(data.additionalInfo.age+' years old');
                            else{
                                if( data.additionalInfo.sex == 'K' )
                                    $('.product.genderage h2').text('According to her age');
                                else
                                    $('.product.genderage h2').text('According to his age');
                            }
                        
                            $.each(data.genderage, function(i, n){
                                var product = slide.clone();
                                product.find('h3').text(n.title);
                                product.find('img.product_photo').attr('src', n.mediumimagelink);
                                product.find('a').attr('href', n.amazonurl);
                                product.find('a').attr('dir', n.id);
                                $('.product.genderage .wrapper').append(product);
                            });
                            $('.product.genderage').show();
                        }
                        
                                                
                        // Show extra form + extra condition
                        if(show_quiz){
                            if( $('#extra-form label[for=age]').css('display') == 'block'  || $('#extra-form label[for=likes]').css('display') == 'block' ){
                                if( data.likes == null ||  data.gender == null ||  data.genderage == null){
                                    $('.friends_avatars, .friends_avatars_label').hide();
                                    $('#extra-form').show();
                                }
                            }else{
                                $('.friends_avatars, .friends_avatars_label').show();
                            }
                        }
                        
                        // show 'help santa' box'
                        $('.presents>div.connect').show();
                        recalc_sliders();
                        $('.presents>div.loading').hide();
                    }, "json");
                }
            
            });
            
            
            var my_friends = new Array();
            
            window.fbAsyncInit = function() {
                // init the FB JS SDK
                FB.init({
                    appId      : '<?php echo $app_id; ?>', // App ID from the App Dashboard
                    channelUrl : '<?php echo $channel_uri; ?>', // Channel File for x-domain communication
                    status     : true, // check the login status upon init?
                    cookie     : true, // set sessions cookies to allow your server to access the session?
                    xfbml      : true  // parse XFBML tags on this page?
                });

                FB.getLoginStatus(function(response) {
                    //console.log(response);
                    window.user_id = response.authResponse.userID;
                    if (response.status === 'connected') {
                        var uid = response.authResponse.userID;
                        var accessToken = response.authResponse.accessToken;
                        
                        FB.api('/me/friends', function(response) {
                            
                            $.each(response.data, function(index, value){
                                value["label"] = value.name;
                                if(index<=17){
                                    var url = 'https://graph.facebook.com/'+value.id+'/picture';
                                    $('.friends_avatars').append('<img style="opacity:0" src="'+url+'" data="'+index+'" alt="'+value.name+'"/>');
                                }
                            });
                            $('.friends_avatars img').each(function(index){
                                // apend animation
                                $(this).delay(index*50).animate({
                                    opacity: '1'
                                }, 1000);
                                // click on avatar action
                                $(this).click(function(){
                                    var id = $(this).attr('data');
                                    $( "#xlInput.search" ).val(response.data[id].name);
                                    window.startLoading(response.data[id].name, response.data[id].id);
                                    
                                });
                            });
                            
                            //Load friend on start
                            if($('.presents.you').size() == 0){
                                var random_friend_id = Math.floor((Math.random()*response.data.length)+1);
                                window.startLoading(response.data[random_friend_id].name, response.data[random_friend_id].id, undefined, undefined, undefined, false);
                            }
                            
                            $( "#xlInput.search" ).autocomplete({
                                minLength: 0,
                                source: response.data,
                                focus: function( event, ui ) {
                                    $( this ).val( ui.item.name );
                                    return false;
                                },
                                select: function( event, ui ) {
                                    
                                    $( this ).val( ui.item.name );
                                    window.startLoading(ui.item.name, ui.item.id);
                            
                                    $('.friends_avatars, .friends_avatars_label').animate({
                                        opacity: '0'
                                    }, function(){ $(this).hide(); $(this).css('opacity', '1'); })
                                    
                                    return false;
                                }
                            }).parents('form').submit(function(){ return false; });
                        });
                        
                    } else if (response.status === 'not_authorized') {
                    } else {
                    }
                });

            };

            (function(d, debug){
                var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
                if (d.getElementById(id)) {
                    return;
                }
                js = d.createElement('script');
                js.id = id;
                js.async = true;
                js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
                ref.parentNode.insertBefore(js, ref);
            }(document, /*debug*/ false));

        </script>

        <header>
            <div class="container canvas">
                <h1>Find gifts for Christmas</h1>
            </div>
        </header>

